// 在所有代码之前定义 showContent 函数
function showContent(contentId) {
    // 隐藏所有内容部分
    const sections = document.querySelectorAll('.section');
    sections.forEach(section => {
        section.style.display = 'none';
    });

    // 显示当前点击的内容
    const selectedSection = document.getElementById(contentId);
    if (selectedSection) {
        selectedSection.style.display = 'block';
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const userAvatar = document.getElementById('userAvatar');
    const usernameField = document.getElementById('username');
    const emailField = document.getElementById('email');
    const phoneField = document.getElementById('phone');
    const genderField = document.getElementById('gender');
    const descriptionField = document.getElementById('description');

    // 从服务器获取用户信息
    fetch('/api/user-info', {
        method: 'GET',
        credentials: 'include'
    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            const userInfo = data.data;

            const avatarUrl = userInfo.avatarUrl || '/resource/avatar/default-avatar.png';
            userAvatar.src = avatarUrl;

            usernameField.textContent = userInfo.username;
            emailField.textContent = userInfo.email;
            phoneField.textContent = userInfo.phone;
            genderField.textContent = userInfo.gender;
            descriptionField.textContent = userInfo.description;

            // 点击“编辑信息”按钮时，填充表单并显示编辑区域
            document.getElementById('editProfileLink').addEventListener('click', function () {
                showContent('edit');
                document.getElementById('newName').value = userInfo.username;
                document.getElementById('newEmail').value = userInfo.email;
                document.getElementById('newPhone').value = userInfo.phone;
                document.getElementById('newGender').value = userInfo.gender;
                document.getElementById('newDescription').value = userInfo.description;
            });
        })
        .catch(error => console.error('Error fetching user info:', error));

    // 提交编辑表单
    document.getElementById('editForm').addEventListener('submit', function (event) {
        event.preventDefault();

        const formData = new FormData();
        const newAvatar = document.getElementById('newAvatar').files[0];

        // 添加头像文件到 FormData
        if (newAvatar) {
            formData.append('avatar', newAvatar);
        }

        // 添加其他用户信息
        formData.append('username', document.getElementById('newName').value.trim());
        formData.append('email', document.getElementById('newEmail').value.trim());
        formData.append('phone', document.getElementById('newPhone').value.trim());
        formData.append('gender', document.getElementById('newGender').value);
        formData.append('description', document.getElementById('newDescription').value.trim());

        // 验证数据完整性
        if (!formData.get('username') || !formData.get('email')) {
            alert('请确保姓名和邮箱字段填写完整！');
            return;
        }

        // 发送更新请求到服务器
        fetch('/api/update-user-info', {
            method: 'POST',
            body: formData,
            credentials: 'include'
        })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    const updatedUserInfo = data.userInfo;

                    usernameField.textContent = updatedUserInfo.username;
                    emailField.textContent = updatedUserInfo.email;
                    phoneField.textContent = updatedUserInfo.phone;
                    genderField.textContent = updatedUserInfo.gender;
                    descriptionField.textContent = updatedUserInfo.description;

                    const updatedAvatarUrl = updatedUserInfo.avatar || userAvatar.src;
                    userAvatar.src = updatedAvatarUrl;

                    // 切换回“个人信息”部分
                    showContent('profile');
                } else {
                    console.error('Error updating user info:', data.message);
                    alert('更新失败: ' + data.message);
                }
            })
            .catch(error => console.error('Error updating user info:', error));
    });

    // 登出用户
    document.querySelector('#logoutLink').addEventListener('click', function (event) {
        event.preventDefault();

        if (confirm('确定要退出账户吗？')) {
            fetch('/api/logout', {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    if (response.redirected) {
                        window.location.href = response.url;
                    }
                })
                .catch(error => console.error('登出请求失败:', error));
        }
    });

    // 注销账户
    document.querySelector('#logoffLink').addEventListener('click', function (event) {
        event.preventDefault();

        if (confirm('确定要注销账户吗？')) {
            fetch('/api/log-off', {
                method: 'POST',
                credentials: 'include'
            })
                .then(response => {
                    if (response.redirected) {
                        window.location.href = response.url;
                    }
                })
                .catch(error => console.error('注销请求失败:', error));
        }
    });

    // 页面加载时默认显示“个人信息”部分
    showContent('profile');
});
